package com.socket.client.handler.message.impl;

import cn.hutool.core.util.StrUtil;
import com.socket.client.handler.message.base.BaseSysMessageHandler;
import com.socket.client.model.base.BaseUser;
import com.socket.client.model.chat.ChatMessage;
import com.socket.client.model.chat.ChatUser;
import com.socket.client.model.enums.OnlineState;
import com.socket.core.model.command.enmus.Command;
import com.socket.core.model.command.enmus.SysLevel;
import com.socket.core.util.Enums;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 系统内置消息执行器
 */
@Slf4j
@Component
public class SysMessageHandler extends BaseSysMessageHandler<Command> {

    @Override
    protected void parse(ChatMessage message, Command command, ChatUser self, BaseUser target) {
        switch (command) {
            case CHANGE:
                String state = message.getContent();
                self.setOnline(Enums.of(OnlineState.class, state));
                userManager.sendAll(state, Command.CHANGE, self);
                break;
            case CHOOSE:
                String suid = self.getGuid(), tuid = message.getTarget();
                // 检查目标是否存在
                if (authnManager.notHas(tuid)) {
                    String tips = StrUtil.format("目标{}不存在", message.isGroup() ? "群组" : "用户");
                    self.send(tips, SysLevel.WARNING);
                    break;
                }
                self.setChoose(tuid);
                // 已读消息处理
                if (!message.isGroup() && userManager.getUnreads(suid, tuid) > 0) {
                    userManager.readAllMessage(suid, tuid, false);
                }
                break;
            case LIST:
                List<String> guids = userManager.getOnlineGuids();
                self.send(Command.LIST.name(), Command.LIST, guids);
                break;
            default:
                // do nothing
        }
    }
}
